export interface User {
  id: string
  name: string
  email: string
  role: "admin" | "user"
  status: "active" | "inactive"
  createdAt: string
  lastLogin: string
}

export interface Workflow {
  id: string
  name: string
  type: "dify" | "coze" | "langgraph"
  status: "active" | "draft" | "archived"
  lastRun: string
  createdAt: string
  nodes: WorkflowNode[]
  edges: WorkflowEdge[] // 添加连线数组
  code?: string // 为 LangGraph 添加代码字段
}

export interface WorkflowNode {
  id: string
  type: string
  label: string
  x: number
  y: number
  config?: Record<string, any>
}

export interface WorkflowEdge {
  id: string
  source: string
  target: string
  sourceHandle?: string
  targetHandle?: string
}

export interface Agent {
  id: string
  name: string
  status: "active" | "draft"
  lastRun: string
  createdAt: string
  components: AgentComponent[]
  edges: AgentEdge[] // 添加连线数组
}

export interface AgentComponent {
  id: string
  type: string
  label: string
  x: number
  y: number
  config?: Record<string, any>
}

export interface AgentEdge {
  id: string
  source: string
  target: string
}

export interface MCP {
  id: string
  name: string
  description: string
  status: "connected" | "error" | "disconnected"
  version: string
  lastSync: string
  endpoints: number
  category?: string
  downloads?: string
  rating?: number
}

// LocalStorage keys
const STORAGE_KEYS = {
  USERS: "app_users",
  WORKFLOWS: "app_workflows",
  AGENTS: "app_agents",
  MCPS: "app_mcps",
}

// Helper functions
function getFromStorage<T>(key: string, defaultValue: T): T {
  if (typeof window === "undefined") return defaultValue
  const stored = localStorage.getItem(key)
  return stored ? JSON.parse(stored) : defaultValue
}

function saveToStorage<T>(key: string, value: T): void {
  if (typeof window === "undefined") return
  localStorage.setItem(key, JSON.stringify(value))
}

// Initial data
const initialUsers: User[] = [
  {
    id: "1",
    name: "张三",
    email: "zhangsan@example.com",
    role: "admin",
    status: "active",
    createdAt: "2024-01-15",
    lastLogin: "2 分钟前",
  },
  {
    id: "2",
    name: "李四",
    email: "lisi@example.com",
    role: "user",
    status: "active",
    createdAt: "2024-02-20",
    lastLogin: "1 小时前",
  },
]

const initialWorkflows: Workflow[] = [
  {
    id: "1",
    name: "客户服务工作流",
    type: "dify",
    status: "active",
    lastRun: "5 分钟前",
    createdAt: "2024-03-01",
    nodes: [],
    edges: [], // 初始化连线数组
  },
  {
    id: "2",
    name: "数据处理流程",
    type: "langgraph",
    status: "draft",
    lastRun: "从未运行",
    createdAt: "2024-03-15",
    nodes: [],
    edges: [], // 初始化连线数组
    code: `from langgraph.graph import StateGraph, END
from typing import TypedDict

class State(TypedDict):
    messages: list[str]
    
def process_node(state: State):
    return {"messages": state["messages"] + ["Processed"]}

workflow = StateGraph(State)
workflow.add_node("process", process_node)
workflow.set_entry_point("process")
workflow.add_edge("process", END)

app = workflow.compile()`,
  },
]

const initialAgents: Agent[] = [
  {
    id: "1",
    name: "智能客服 Agent",
    status: "active",
    lastRun: "10 分钟前",
    createdAt: "2024-03-01",
    components: [],
    edges: [], // 初始化连线数组
  },
  {
    id: "2",
    name: "数据分析 Agent",
    status: "draft",
    lastRun: "从未运行",
    createdAt: "2024-03-10",
    components: [],
    edges: [], // 初始化连线数组
  },
]

const initialMCPs: MCP[] = [
  {
    id: "1",
    name: "Slack MCP",
    description: "连接到 Slack 工作区，读取和发送消息",
    status: "connected",
    version: "1.2.0",
    lastSync: "2 分钟前",
    endpoints: 5,
  },
  {
    id: "2",
    name: "GitHub MCP",
    description: "访问 GitHub 仓库、Issues 和 Pull Requests",
    status: "connected",
    version: "2.0.1",
    lastSync: "15 分钟前",
    endpoints: 8,
  },
]

// Data management functions
export const mockData = {
  // Users
  getUsers: (): User[] => getFromStorage(STORAGE_KEYS.USERS, initialUsers),
  saveUsers: (users: User[]) => saveToStorage(STORAGE_KEYS.USERS, users),
  addUser: (user: Omit<User, "id">) => {
    const users = mockData.getUsers()
    const newUser = { ...user, id: Date.now().toString() }
    mockData.saveUsers([...users, newUser])
    return newUser
  },
  updateUser: (id: string, updates: Partial<User>) => {
    const users = mockData.getUsers()
    const updated = users.map((u) => (u.id === id ? { ...u, ...updates } : u))
    mockData.saveUsers(updated)
  },
  deleteUser: (id: string) => {
    const users = mockData.getUsers()
    mockData.saveUsers(users.filter((u) => u.id !== id))
  },

  // Workflows
  getWorkflows: (): Workflow[] => getFromStorage(STORAGE_KEYS.WORKFLOWS, initialWorkflows),
  saveWorkflows: (workflows: Workflow[]) => saveToStorage(STORAGE_KEYS.WORKFLOWS, workflows),
  addWorkflow: (workflow: Omit<Workflow, "id">) => {
    const workflows = mockData.getWorkflows()
    const newWorkflow = { ...workflow, id: Date.now().toString() }
    mockData.saveWorkflows([...workflows, newWorkflow])
    return newWorkflow
  },
  updateWorkflow: (id: string, updates: Partial<Workflow>) => {
    const workflows = mockData.getWorkflows()
    const updated = workflows.map((w) => (w.id === id ? { ...w, ...updates } : w))
    mockData.saveWorkflows(updated)
  },
  deleteWorkflow: (id: string) => {
    const workflows = mockData.getWorkflows()
    mockData.saveWorkflows(workflows.filter((w) => w.id !== id))
  },
  getWorkflow: (id: string): Workflow | undefined => {
    return mockData.getWorkflows().find((w) => w.id === id)
  },

  // Agents
  getAgents: (): Agent[] => getFromStorage(STORAGE_KEYS.AGENTS, initialAgents),
  saveAgents: (agents: Agent[]) => saveToStorage(STORAGE_KEYS.AGENTS, agents),
  addAgent: (agent: Omit<Agent, "id">) => {
    const agents = mockData.getAgents()
    const newAgent = { ...agent, id: Date.now().toString() }
    mockData.saveAgents([...agents, newAgent])
    return newAgent
  },
  updateAgent: (id: string, updates: Partial<Agent>) => {
    const agents = mockData.getAgents()
    const updated = agents.map((a) => (a.id === id ? { ...a, ...updates } : a))
    mockData.saveAgents(updated)
  },
  deleteAgent: (id: string) => {
    const agents = mockData.getAgents()
    mockData.saveAgents(agents.filter((a) => a.id !== id))
  },
  getAgent: (id: string): Agent | undefined => {
    return mockData.getAgents().find((a) => a.id === id)
  },

  // MCPs
  getMCPs: (): MCP[] => getFromStorage(STORAGE_KEYS.MCPS, initialMCPs),
  saveMCPs: (mcps: MCP[]) => saveToStorage(STORAGE_KEYS.MCPS, mcps),
  addMCP: (mcp: Omit<MCP, "id">) => {
    const mcps = mockData.getMCPs()
    const newMCP = { ...mcp, id: Date.now().toString() }
    mockData.saveMCPs([...mcps, newMCP])
    return newMCP
  },
  updateMCP: (id: string, updates: Partial<MCP>) => {
    const mcps = mockData.getMCPs()
    const updated = mcps.map((m) => (m.id === id ? { ...m, ...updates } : m))
    mockData.saveMCPs(updated)
  },
  deleteMCP: (id: string) => {
    const mcps = mockData.getMCPs()
    mockData.saveMCPs(mcps.filter((m) => m.id !== id))
  },
}
